## 接口权限

import json
import re

from django.utils.deprecation import MiddlewareMixin
from rest_framework import response

# from component.RedisModel import r
# from common.models import *
from .models import User
# from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse, HttpResponse


class ValidPermission(MiddlewareMixin):

    def process_request(self, request):
        currentUrl = request.path_info
        method = request.method.lower()
        # print('currentUrl:', currentUrl, '\nmethod:', method)

        ## 不对登录接口做验证
        ## if currentUrl == '/api/CreateToken/' or re.match('/admin', currentUrl ):
        # return None

        ## 白名单
        white_list = [
            '/api/IdaasJwt/',
            '/api/temp111/',
            '/admin',
            '/apis/rbac/login/',
            '/docs/'
        ]

        ## 不对登录接口做验证
        for item in white_list:
            if re.match(item, currentUrl):
                return None

        # print('进来api接口验证了')
        username = request.META.get("HTTP_USERNAME")
        # print('username.xxx:', username)

        # # 获取接口权限列表
        userobj = User.objects.filter(username=username).first()

        if not userobj:
            return JsonResponse({"type": "error", "msg": "请在请求头携带 username 参数"})

        # print("aaa", userobj.groups.all().values_list("interfacepaths__path", flat=True).distinct())

        # permissionlist = list(
        #     userobj.roles.all().values("permissions__url", "permissions__action", "permissions__title",
        #                                "permissions__group__title").distinct())
        permissionlist = list(userobj.groups.all().values_list("interfacepaths__path", flat=True).distinct())
        print(permissionlist)

        # for item in permissionlist:
        #     if currentUrl == item['permissions__url'] and method == item['permissions__action']:
        #         return None

        for item in permissionlist:
            res = item.split(":")
            if currentUrl == res[0] and method == res[1]:
                return None

        return JsonResponse({"type": "error", "msg": "没有权限"})